<template>
  <div class="content">
    <el-card class="box-card">
      <div class="search-holder">
        <el-form ref="searchForm" label-width="80px" :model="searchVal" size="mini">
          <el-row :gutter="20">
            <el-col :span="6" :offset="0">
              <el-form-item label="昵称">
                <el-input v-model="searchVal.nickName" placeholder="昵称模糊查询" />
              </el-form-item>
            </el-col>
            <el-col :span="6" :offset="0">
              <el-form-item label="用户名">
                <el-input v-model="searchVal.username" placeholder="用户名模糊查询" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :offset="16" :span="6">
              <el-form-item>
                <el-button @click="reset">重置</el-button>
                <el-button type="primary" @click="search">查询</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </el-card>

    <el-card shadow="always" :body-style="{ padding: '20px' }">
      <!-- 新增用户按钮 -->
      <div slot="header">
        <el-button
          type="primary"
          size="small"
          @click="addUser"
        >新增</el-button>
      </div>

      <div class="table-holder">
        <!-- 用户展示表格 -->
        <el-table :data="userList" border style="width: 100%">
          <el-table-column fixed="left" type="index" label="#" width="50" />
          <el-table-column prop="username" label="用户名" width="200" />
          <el-table-column prop="nick_name" label="昵称" width="200" />
          <el-table-column label="头像" width="200">
            <template slot-scope="scope">
              <img class="image" :src="scope.row.salt" alt="">
            </template>
          </el-table-column>
          <el-table-column prop="roles" label="角色" />
          <el-table-column prop="create_time" label="添加时间" width="200" />
          <el-table-column fixed="right" label="操作" width="200">
            <template slot-scope="scope">
              <el-button
                type="success"
                size="small"
                @click="editUser(scope.row)"
              >编辑</el-button>
              <el-button
                type="danger"
                size="small"
                @click="remove(scope.row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页器 -->
      <div class="pagination-holder">
        <el-pagination
          :current-page="page.start"
          :page-sizes="page.pageSize"
          :page-size="page.limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增编辑用户弹窗 -->
    <el-dialog title="编辑用户" :visible.sync="dialogFormVisible" width="30%">

      <el-form ref="userForm" :model="userInfo" :rules="rules" label-width="100px" class="demo-ruleForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userInfo.username" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickName">
          <el-input v-model="userInfo.nickName" />
        </el-form-item>
        <el-form-item v-if="isAdd" label="密码" prop="password">
          <el-input v-model="userInfo.password " />
        </el-form-item>
        <el-form-item label="用户头像" prop="avatar">
          <div class="upload-holder">
            <el-upload
              class="avatar-uploader"
              :action="uploadUrl"
              :headers="uploadHeaders"
              :on-success="uploadSuccess"
              :limit="1"
              :show-file-list="false"
            >
              <img
                v-if="userInfo.salt"
                :src="userInfo.salt"
                class="avatar"
              >
              <i v-else class="el-icon-plus avatar-uploader-icon" />
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="选择角色" prop="roleId">
          <el-select v-model="userInfo.roleIds" clearable multiple placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button
          type="primary"
          @click="submit"
        >确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  requestUserList,
  deleteUser,
  requestRolesList,
  addUser,
  updataUser,
  requesttUserInfo
} from '@/api/auth'
import mixin from '@/mixins/index'
export default {
  mixins: [mixin],
  data() {
    return {
      // 用户列表
      userList: [],
      // 用户信息
      userInfo: {
        roleIds: []
      },
      // 角色列表
      rolesList: [],
      // 用户搜索内容
      searchVal: {
        username: '',
        nickName: ''
      },
      dialogFormVisible: false,
      isAdd: false,
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        nickName: [
          { required: true, message: '请输入昵称', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        roleId: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    dialogFormVisible(val) {
      if (!val) {
        this.userInfo = {}
      }
    }
  },
  created() {
    this.getUserList()
    this.getRolesList()
  },
  methods: {
    // 上传头像成功的钩子
    uploadSuccess(res) {
      // console.log(res)
      if (res.code === 20000) {
        this.$set(this.userInfo, 'salt', res.data.fileUrl)
      }
    },
    // 添加用户请求
    addUserMethod() {
      addUser(this.userInfo).then(res => {
        if (res.code === 20000) {
          this.$message({
            type: 'success',
            message: '添加成功!'
          })
          this.dialogFormVisible = false
          this.getUserList()
        } else {
          this.$message({
            type: 'error',
            message: '添加失败!'
          })
        }
      })
    },
    // 更新用户请求
    updataUserMethod() {
      updataUser(this.userInfo).then(res => {
        console.log(res)
        if (res.code === 20000) {
          this.$message({
            type: 'success',
            message: '修改成功!'
          })
          this.dialogFormVisible = false
          this.getUserList()
        } else {
          this.$message({
            type: 'error',
            message: '修改失败!'
          })
        }
      })
    },
    // 提交
    submit() {
      console.log(this.userInfo)
      if (this.isAdd) {
        this.addUserMethod()
      } else {
        this.updataUserMethod()
      }
    },
    // 关闭弹窗
    close() {
      this.dialogFormVisible = false
    },
    // 重置搜索结果
    reset() {
      this.articleSearch = {
        title: '',
        author: ''
      }
      this.getUserList()
    },
    // 搜索
    search() {
      this.page.start = 0
      this.getUserList()
    },
    // 获取用户列表信息
    getUserList() {
      requestUserList(this.page).then((res) => {
        this.page.total = res.data.total
        this.userList = res.data.rows
        console.log(res)
      })
    },
    // 获取角色列表
    getRolesList() {
      requestRolesList().then(res => {
        // console.log(res)
        this.rolesList = res.data.items
      })
    },
    // 弹出添加弹框
    // 新增用户
    addUser() {
      this.dialogFormVisible = true
      this.isAdd = true
    },
    // 编辑用户
    editUser(item) {
      this.isAdd = false
      requesttUserInfo(item.id).then(res => {
        console.log(res)
        this.userInfo = res.data.user
        this.dialogFormVisible = true
      })
    },
    // 改变每页数量
    handleSizeChange(val) {
      this.page.limit = val
      this.getUserList()
    },
    // 改变页码
    handleCurrentChange(val) {
      this.page.start = val
      this.getUserList()
    },
    // 删除
    remove(id) {
      console.log(id)
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteUser(id).then((res) => {
            // console.log(res);
            if (res.code === 20000) {
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
              this.getUserList()
            } else {
              this.$message({
                type: 'error',
                message: '删除失败'
              })
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    }
  }
}
</script>

@import '@/style/index.scss'

<style scoped>
.avatar-uploader .el-upload {
  border-radius: 50%;
  border: 1px dashed #d9d9d9;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  border-radius: 50%;
  font-size: 28px;
  color: #8c939d;
  width: 50px;
  height: 50px;
  line-height: 50px;
  text-align: center;
}
.avatar {
  border-radius: 50%;
  width: 50px;
  height: 50px;
  display: block;
}
</style>

<style lang="scss" scoped>
.content {
  .image {
    width: 100px;
    height: 100px;
  }

  .input-holder{
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 80%;

    span{
      width: 50px;
    }
  }
}
</style>
